//
//  LFHomeVM.m
//  College
//
//  Created by LF on 2018/11/7.
//  Copyright © 2018 MuXi. All rights reserved.
//

#import "LFHomeVM.h"

@implementation LFHomeVM

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.net.model_name = NSStringFromClass([Food class]);
        self.net.api = API_FOOD;
    }
    return self;
}

-(void)lf_initialize {
    @weakify(self)
    [self.loadDatasSubject subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        [self.getList execute:nil];
    }];
}

- (RACCommand *)addFood {
    if (!_addFood) {
        _addFood = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                [LFNetworkTool httpRequest:1 url:API_APPEND_(API_FOOD) para:@{@"name":input} success:^(id json) {
                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableContainers error:nil];
                    if ([dic[@"code"] intValue] == 1) {
                        ShowSuccessStatus(dic[@"msg"]);
                        [self.getList execute:nil];
                    } else {
                        [LFReminderTool showErrorWithStatus:dic[@"msg"]];
                    }
                    [subscriber sendNext: nil];
                    [subscriber sendCompleted];
                } failure:^(NSError *error) {
                    ShowErrorStatus(error);
                }];
                return nil;
            }];
        }];
    }
    return _addFood;
}

- (NSTimer *)timer {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 repeats:YES block:^(NSTimer * _Nonnull timer) {
            NSUInteger index = random() % self.datas.count;
            for (Food *food in self.datas) {
                if (index == [self.datas indexOfObject:food]) {
                    food.status = 0;
                } else {
                    food.status = 1;
                }
            }
            [self.refreshUISubject sendNext:nil];
        }];
    }
    return _timer;
}

@end
